package StringPackage;

/**
 * @author Lzm
 * @version 1.0
 */
public class reverseWords {
  public static void main(String[] args) {
    String s = "hello   word";
    s = takeString(s);
    s = reverseString(s);
    s = reverseWord(s);
    System.out.println(s);
  }

  public static String reverseString(String s){
    char[] chars = s.toCharArray();
    int slow = 0;
    for (int fast = s.length() - 1 ; fast >= s.length() / 2 ; fast --){
        char temp = chars[slow];
        chars[slow++] = chars[fast];
        chars[fast] = temp;

    }
    return new String(chars);
  }
  /*双指针法 删除多余空格*/
  public static String takeString(String s){
    int slow = 0;
    char[] chars = s.toCharArray();
    for (int fast = 0 ; fast < chars.length ; fast ++){
      if (chars[fast] != ' '){
        if (slow != 0 && chars[fast - 1] == ' '){
          chars[slow++] = ' ';
        }
          chars[slow++] = chars[fast];
      }
    }
    return new String(chars,0,slow);
  }

  public static String reverse(String s,int begin,int end){
    char[] chars = s.toCharArray();
    int left = begin;
    int right = end - 1;
    /*对字符串进行反转*/
    while(left < right){
      char temp = chars[left];
      chars[left++] = chars[right];
      chars[right--] = temp;
    }
    return new String (chars);
  }
  public static String reverseWord(String s){
    String result = "";
    String[] strings = s.split(" ");
    for (int i = 0 ; i < strings.length ; i ++){
      strings[i] = reverse(strings[i],0,strings[i].length());
      if (i == strings.length - 1){
        result += strings[i];
      }
      else{
        result += strings[i] + " ";
      }
    }
    return result;
  }
}
